1
The Grammar of Strings: Defining Patterns with RegExp
AI020 Lesson 5
00:00

Regular Expressions (RegExp) are a specialized formal grammar used to describe, match, and manipulate patterns within string data. In JavaScript, a RegExp acts as a blueprint for the engine to perform search-and-validate operations.

1. Defining the Grammar

There are two primary ways to instantiate a pattern: the literal notation (var re2 = /abc/;), compiled when the script loads, and the RegExp constructor (var re1 = new RegExp("abc");), which allows for building patterns dynamically from variables.

/abc/Literal (Fast/Static)new RegExp("abc")Constructor (Dynamic)

2. The .test() Method

The .test() method is the most fundamental way to apply this grammar; it returns a Boolean indicating if the pattern exists anywhere within the target string. Certain characters like + have functional meanings and must be escaped with a backslash (e.g., /eighteen\+/) to be matched literally.

main.py
TERMINAL bash — 80x24
> Ready. Click "Run" to execute.
>